package net.java.nioserver.aio;

import net.java.nioserver.utils.ChannelUtil;
import net.jcip.annotations.ThreadSafe;

import java.nio.channels.SocketChannel;
import java.nio.channels.Selector;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Leonid Shlyapnikov
 */
@ThreadSafe
class BasicAioOpAccept {
    
    private static final Logger log = LoggerFactory.getLogger(BasicAioOpAccept.class);

    public SocketChannel handle(ServerSocketChannel ssc, Selector selector) throws IOException {

        SocketChannel sc = ssc.accept();

        if (null == sc) {
            log.warn("SocketChannel is null");
            return null;
        }

        try {
            sc.configureBlocking(false);
            sc.register(selector, SelectionKey.OP_READ);

            if (log.isInfoEnabled()) {
                log.info("New connection accepted: " + sc);
            }
        } catch (Exception e) {
            log.error("Cannot accept connection: " + sc, e);
            ChannelUtil.close(sc);
        }

        return sc;
    }
}
